package com.bdjk.bdmw.InfoGath.communication.server.tcp.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;

public class TCPServerHandler 	extends ChannelInboundHandlerAdapter{
  private static Map<String, Channel> map = new HashMap();
  private static List<Channel> channel = new ArrayList();
  private static final Logger logger = Logger.getLogger(TCPServerHandler.class);
  
  public void channelRegistered(ChannelHandlerContext ctx)
    throws Exception
  {
    super.channelRegistered(ctx);
    channel.add(ctx.channel());
  }
  
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
  {
    ByteBuf result = (ByteBuf)msg;
    byte[] result1 = new byte[result.readableBytes()];
    
    result.readBytes(result1);
    String resultStr = new String(result1);
    logger.info("Server--------" + msg + "---------");
    System.out.println("Client said:" + resultStr);
    
    result.release();
    new Thread(new CommThread(resultStr, ctx.channel(), map)).start();
  }
  
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
    super.channelReadComplete(ctx);
    ctx.flush();
  }
}